<?php
namespace app\store\model\store;

use app\api\model\UserExt;
use app\common\model\BaseModel;
use app\store\model\User as UserModel;

class Dermember extends BaseModel{
    // 定义表名
    protected $name = 'dermember';

    // 定义主键
    protected $pk = 'id';

    // 用户关联数据
    public function user(){
        return $this->hasOne(UserModel::class,'user_id','id')
            ->bind(['mobile','nick_name','avatar_id','pay_money','expend_money']);
    }
    // perform关联数据
    public function perform(){
        return $this->belongsTo(Perform::class,'perform_id','id')
            ->bind(['performance','award']);
    }
    //经销商列表
    public function getList($param){
        $oder = 'desc';
        if(isset($param['orderType'])){
            $oder = $param['orderType'];
        }
        if(isset($param['idCard']) && !empty($param['idCard'])){
            $r = self::with('user')
                ->whereLike('idCard',"%{$param['idCard']}%")
                ->order('create_time',$oder)
                ->paginate($param['limit']);
        }else{
            $r = self::with('user')
                ->order('create_time',$oder)
                ->paginate($param['limit']);
        }
        return $r;
    }
    //获取经销商个人达标奖金
    private function getDBAward($perform_id){
        $performModel = new Perform();
        return $performModel->where(['id'=>$perform_id])->find();
    }
    //获得经销商奖励
    public function getAward($id){
        $r = self::where(['id'=>$id])->with('user')->find();
        $perform_id = $r['perform_id'];
        //达标奖励
        $getDBAward = $this->getDBAward($perform_id);
        return [
            //达标奖励
            'DBAward'=>$getDBAward,
            //个人销售额
            'pay_money' => $r['pay_money'],
            //团队收益
            'total_expend_money'=>$r['total_expend_money'],
            //团队成员人数
            'pcount'=>$r['pcount']
        ];
    }

    //关联用户扩展表
    /*public function userext(){
        return $this->hasOne(UserExt::class,'idCard','idCard')
            ->bind(['user_id_ext'=>'user_id']);
    }*/
    // 更新user_id
    /*public function updateUserId($idCard){
        $r = self::where(['idCard'=>$idCard])->with('userext')->findOrEmpty();
        if($r->isEmpty()){
            return false;
        }
        $user_id_ext = $r['user_id_ext'];
        return self::where(['idCard'=>$idCard])->save(['user_id'=>$user_id_ext]);
    }*/
}
